$(function() {
	//set the draggable and droppable elements
	$('#app-elements div').draggable({
		containment: "#event-controls",
		cursor: "move",
		revert: true
	});
	$('#device-screen').droppable({
		accept: "#app-elements div",
		tolerance: "touch",
		drop: handleDrop
	});
	
	//Functions to handle clicks on amendable text
	$('#app-title-text').click(function(){
		elementId = $(this).attr('id');
		//Set the dialog header and label
		$('.ui-dialog-title').text('App page title editor');
		$('#dialog-single-input-label').text('App page title:');
		//Set the dialog passed data and open dialog
		$('#dialog-single-input').data('elementId', elementId);
		$('#dialog-single-input').data('inputType', 'page title');
		$('#dialog-single-input').data('inputMaxLength', '40');
		$('#dialog-single-input').dialog('open');
	});
	
	//Input dialog
	$('#dialog-single-input').dialog({
		autoOpen: false,
		height: 300,
		width: 400,
		modal: true,
		buttons: {
			"Update": function() {
				validInput = true;
				outputTo = $(this).data('elementId');
				inputType = $(this).data('inputType');
				inputMaxLength = $(this).data('inputMaxLength');
				attr = $(this).data('attr');
				regexInput = $(this).data('regex');
				regex = new RegExp(regexInput);
				input = $('#dialog-single-input-text');
				input.removeClass("ui-state-error");
				validInput = validInput && checkLength(input, inputType, 2, inputMaxLength);
				if (regexInput != null) {
					validInput = validInput && checkRegex(regex, input, inputType);
				}
				if (validInput) {
					if (attr != null) {
						$('#' + outputTo).attr(attr, input.val());
					} else {
						$('#' + outputTo).text(input.val());
					}
					if (inputType=="page title") {
						$('#app-title-text').css('color','#FFFFFF');
					}
					if (attr=='data-href') {
						$('#' + outputTo).parent().attr('src', input.val());
						gapi.plus.go('#' + outputTo);
					}
					$(this).dialog('close');
				}
			},
			"Cancel": function() {
				$(this).dialog('close');
			}
		},
		close: function() {
			$('#dialog-single-input-text').val("").removeClass("ui-state-error");
			$('#dialog-single-input-text').attr('rows', '1');
			//Reset data attributes
			$('#dialog-single-input').data('elementId', null);
			$('#dialog-single-input').data('inputType', null);
			$('#dialog-single-input').data('inputMaxLength', null);
			$('#dialog-single-input').data('attr', null);
			$('#dialog-single-input').data('regex', null);
		}
	});
	
	
	
});

//Validation
function checkLength(element, name, min, max) {
    if ( element.val().length > max || element.val().length < min ) {
    	element.addClass("ui-state-error");
        updateTips("Length of " + name + " must be between " +
            min + " and " + max + ".");
        return false;
    } else {
        return true;
    }
}
function checkRegex(regex, element, name) {
	if (regex.test(input.val()) == false) {
		element.addClass("ui-state-error");
		updateTips("The " + name + " entered is invalid.");
		return false;
	} else {
		return true;
	}
}
function updateTips(t) {
	tips = $( ".validateTips" );
    tips
        .text(t)
        .addClass( "ui-state-highlight" );
    setTimeout(function() {
        tips.removeClass( "ui-state-highlight", 1500 );
    }, 500 );
}

//Handle drop event for app elements
function handleDrop(event, ui) {
	droppedItem = ui.draggable.attr('id');
	if (droppedItem == "multi-choice-4") {
		createMultiQuestion(4);
	} else if (droppedItem == "multi-choice-3") {
		createMultiQuestion(3);
	} else if (droppedItem == "multi-choice-2") {
		createMultiQuestion(2);
	} else if (droppedItem == "heading3") {
		createHeadingThree();
	} else if (droppedItem == "text") {
		createParagraph();
	} else if (droppedItem == "image") {
		createImage();
	} else if (droppedItem == "tube-status") {
		createTubeStatus();
	} else if (droppedItem == "google-plus") {
		createGooglePlus();
	} else if (droppedItem == "facebook-like") {
		createFacebookLike();
	} else if (droppedItem == "twitter-tweet") {
		createTwitterHash();
	}
}

//Handle deleting an element from the app sim
function removeTwo(element, genericName) {
	//get the id and class of the item to be removed
	removeID = element.parent().parent().attr('id');
	removeClass = element.parent().parent().attr('class');
	//remove the id
	$('#' + removeID).remove();
	//reorder the class
	objects = $('#app-screen-content').find("." + removeClass);
	for (i=0 ; i<objects.length ; i++) {
		object = objects[i];
		newId = String(genericName + (i+1));
		$(object).attr('id', newId);
	}
}

function remove(element) {
	//get the id and class of the item to be removed
	removeID = element.parent().parent().attr('id');
	//remove the id
	$('#' + removeID).remove();
}


//Functions to create app elements
function createMultiQuestion(options) {
	exists = Boolean($('#app-screen-content').find('#app-multi-choice').attr('id'));
	if (exists != true) {
		appendString = '<fieldset id="app-multi-choice">' +
				'<legend><button type="button" class="delete" onclick="remove($(this))">Delete</button>' +
				'<select id="app-points"><option value="null">Points:</option><option value="0">0</option><option value="5">5</option>' + 
				'<option value="10">10</option><option value="15">15</option><option value="20">20</option></select>';
		if (options == 4) {
			appendString += 
				'<select id="app-correct-response"><option value="null">Correct answer:</option><option value="a">A</option>' + 
				'<option value="b">B</option><option value="c">C</option><option value="d">D</option></select>' + 
			'</legend>' +
				'<p class="app" id="app-multi-question">Click here to add your question</p>' +
				'<div class="app-button"><span class="app-button-inner"><span id="app-multi-question-a" class="app-button-text">Click to add answer A</span></span></div>' +
				'<div class="app-button"><span class="app-button-inner"><span id="app-multi-question-b" class="app-button-text">Click to add answer B</span></span></div>' +
				'<div class="app-button"><span class="app-button-inner"><span id="app-multi-question-c" class="app-button-text">Click to add answer C</span></span></div>' +
				'<div class="app-button"><span class="app-button-inner"><span id="app-multi-question-d" class="app-button-text">Click to add answer D</span></span></div>';
		} else if (options == 3) {
			appendString += 
				'<select id="app-correct-response"><option value="null">Correct answer:</option><option value="a">A</option>' + 
				'<option value="b">B</option><option value="c">C</option></select>' + 
			'</legend>' +
				'<p class="app" id="app-multi-question">Click here to add your question</p>' +
				'<div class="app-button"><span class="app-button-inner"><span id="app-multi-question-a" class="app-button-text">Click to add answer A</span></span></div>' +
				'<div class="app-button"><span class="app-button-inner"><span id="app-multi-question-b" class="app-button-text">Click to add answer B</span></span></div>' +
				'<div class="app-button"><span class="app-button-inner"><span id="app-multi-question-c" class="app-button-text">Click to add answer C</span></span></div>';
		} else if (options == 2) {
			appendString += 
				'<select id="app-correct-response"><option value="null">Correct answer:</option><option value="a">A</option>' + 
				'<option value="b">B</option></select>' + 
			'</legend>' +
				'<p class="app" id="app-multi-question">Click here to add your question</p>' +
				'<div class="app-button"><span class="app-button-inner"><span id="app-multi-question-a" class="app-button-text">Click to add answer A</span></span></div>' +
				'<div class="app-button"><span class="app-button-inner"><span id="app-multi-question-b" class="app-button-text">Click to add answer B</span></span></div>';
		}
		
		appendString += '</fieldset>';
		$('#app-screen-content').append(appendString);
		$('#app-multi-question').click(function(){
			elementId = $(this).attr('id');
			//Set the dialog header and label
			$('.ui-dialog-title').text('Question editor');
			$('#dialog-single-input-label').text('Question text:');
			//Set the dialog passed data and open dialog
			$('#dialog-single-input').data('elementId', elementId);
			$('#dialog-single-input').data('inputType', 'question');
			$('#dialog-single-input').data('inputMaxLength', '40');
			$('#dialog-single-input').dialog('open');
		});
		$('.app-button').click(function() {
			elementId = $(this).find('.app-button-text').attr('id');
			qLetter = elementId.substr(elementId.length - 1).toUpperCase();
			//Set the dialog header and label
			$('.ui-dialog-title').text('Answer ' + qLetter + ' response editor');
			$('#dialog-single-input-label').text('Response for answer ' + qLetter + ':');
			//Set the dialog passed data and open dialog
			$('#dialog-single-input').data('elementId', elementId);
			$('#dialog-single-input').data('inputType', 'answer ' + qLetter);
			$('#dialog-single-input').data('inputMaxLength', '40');
			$('#dialog-single-input').dialog('open');
		});
	} else {
		alert("For usability you can only have one multiple choice question per event");
	}
}

function createHeadingThree() {
	count = 0;
	count += $('#app-screen-content').find('.app-heading-three').length;
	count++;
	$('#app-screen-content').append('<fieldset class="app-heading-three" id="app-h3-' + count + '">' + 
			'<legend><button type="button" class="delete" onclick="removeTwo($(this), \'app-h3-\')">Delete</button>Click to edit</legend>' + 
			'<h3 class="app" id="app-heading-three-' + count + '">Click to change text</h3>' + 
			'</fieldset>');
	$('.app-heading-three').click(function(){
		elementId = $(this).find('.app').attr('id');
		//Set the dialog header and label
		$('.ui-dialog-title').text('Heading editor');
		$('#dialog-single-input-label').text('Heading text:');
		//Set the dialog passed data and open dialog
		$('#dialog-single-input').data('elementId', elementId);
		$('#dialog-single-input').data('inputType', 'heading');
		$('#dialog-single-input').data('inputMaxLength', '40');
		$('#dialog-single-input').dialog('open');
	});
}

function createParagraph() {
	count = 0;
	count += $('#app-screen-content').find('.app-paragraph').length;
	count++;
	$('#app-screen-content').append('<fieldset class="app-paragraph" id="app-p-' + count + '">' +
			'<legend><button type="button" class="delete" onclick="removeTwo($(this), \'app-p-\')">Delete</button>Click to edit</legend>' + 
			'<p class="app" id="app-paragraph-' + count + '">Click to change text</p>' + 
			'</fieldset>');
	$('.app-paragraph').click(function(){
		elementId = $(this).find('.app').attr('id');
		//Set the dialog header and label
		$('.ui-dialog-title').text('Paragraph editor');
		$('#dialog-single-input-label').text('Paragraph text:');
		$('#dialog-single-input-text').attr('rows', '4');
		//Set the dialog passed data and open dialog
		$('#dialog-single-input').data('elementId', elementId);
		$('#dialog-single-input').data('inputType', 'paragraph');
		$('#dialog-single-input').data('inputMaxLength', '500');
		$('#dialog-single-input').dialog('open');
	});
}

function createImage() {
	count = 0;
	count += $('#app-screen-content').find('.app-image').length;
	count++;
	$('#app-screen-content').append('<fieldset class="app-image" id="app-img-' + count + '">' +
			'<legend><button type="button" class="delete" onclick="removeTwo($(this), \'app-img-\')">Delete</button>Click to edit</legend>' + 
			'<img class="app" id="app-image-' + count + '" src="" width="100%" alt="click here to add an image" />' + 
			'</fieldset>');
	$('.app-image').click(function(){
		elementId = $(this).find('.app').attr('id');
		//Set the dialog header and label
		$('.ui-dialog-title').text('Image location');
		$('#dialog-single-input-label').text('HTML link to image (must be JPG, JPEG, SVG, GIF, or PNG): (include http://)');
		//Set the dialog passed data and open dialog
		$('#dialog-single-input').data('attr', 'src');
		$('#dialog-single-input').data('elementId', elementId);
		$('#dialog-single-input').data('inputType', 'HTML link');
		$('#dialog-single-input').data('inputMaxLength', '500');
		$('#dialog-single-input').data('regex', "^(http|https)://(\\w+.|\\w+.\\w+.)((\\w|-|_)+/|(\\w|-|_)+.(\\w|-|_)+/)+(\\w|-|_)+(.jpg|.png|.svg|.gif|.jpeg)$");
		$('#dialog-single-input').dialog('open');
	});
}

function createTubeStatus() {
	count = 0;
	count += $('#app-screen-content').find('.app-tube-status').length;
	count++;
	$('#app-screen-content').append('<fieldset class="app-tube-status" id="app-tube-' + count + '">' +
			'<legend><button type="button" class="delete" onclick="removeTwo($(this), \'app-tube-\')">Delete</button></legend>' + 
			'<img class="app" id="app-tube-status-' + count + '" src="http://cdn-www.greenroad.com/media/tfl-logo-hi-res.jpg" />' + 
			'</fieldset>');
}

function createGooglePlus() {
	count = 0;
	count += $('#app-screen-content').find('.app-google-plus').length;
	count++;
	$('#app-screen-content').append('<fieldset class="app-google-plus" id="app-g-plus-' + count + '">' +
			'<legend src=""><button type="button" class="delete" onclick="removeTwo($(this), \'app-g-plus-\')">Delete</button>Click to edit</legend>' + 
			'<div class="app g-plus" id="app-google-plus-' + count + '" data-href="" data-rel="publisher"></div>' + 
			'</fieldset>');
	$('.app-google-plus').click(function(){
		elementId = $(this).find('.app').attr('id');
		//Set the dialog header and label
		$('.ui-dialog-title').text('Google+ profile location');
		$('#dialog-single-input-label').text('HTML link to Google+ profile: (must be full path)');
		//Set the dialog passed data and open dialog
		$('#dialog-single-input').data('attr', 'data-href');
		$('#dialog-single-input').data('elementId', elementId);
		$('#dialog-single-input').data('inputType', 'HTML link');
		$('#dialog-single-input').data('inputMaxLength', '500');
		$('#dialog-single-input').data('regex', "^(http|https)://plus.google.com/(\\w+|\\w+/|\\w+.\\w+/)+\\w*");
		$('#dialog-single-input').dialog('open');
	});
	
}

function createFacebookLike() {
	count = 0;
	count += $('#app-screen-content').find('.app-facebook-like').length;
	count++;
	$('#app-screen-content').append('<fieldset class="app-facebook-like" id="app-f-like-' + count + '">' +
			'<legend><button type="button" class="delete" onclick="removeTwo($(this), \'app-f-like-\')">Delete</button>Click to edit</legend>' + 
			'<img width="80%" src="/images/app-element-facebook.png" alt="Click to add link"/>' + 
			'<p class="apptext">Like URL:</p><p class="app" id="app-facebook-like-' + count + '">No URL added - click to add</p>' +
			'</fieldset>');
	$('.app-facebook-like').click(function(){
		elementId = $(this).find('.app').attr('id');
		//Set the dialog header and label
		$('.ui-dialog-title').text('Link location');
		$('#dialog-single-input-label').text('HTML link to the page to "like" (include http://):');
		//Set the dialog passed data and open dialog
		$('#dialog-single-input').data('elementId', elementId);
		$('#dialog-single-input').data('inputType', 'HTML link');
		$('#dialog-single-input').data('inputMaxLength', '500');
		$('#dialog-single-input').data('regex', "^(http|https)://(\\w+.|\\w+.\\w+.)(\\w+|\\w+.\\w+)+\\w+");
		$('#dialog-single-input').dialog('open');
	});
}

function createTwitterHash() {
	count = 0;
	count += $('#app-screen-content').find('.app-twitter-hash').length;
	count++;
	$('#app-screen-content').append('<fieldset class="app-twitter-hash" id="app-t-hash-' + count + '">' +
			'<legend><button type="button" class="delete" onclick="removeTwo($(this), \'app-t-hash-\')">Delete</button>Click to edit</legend>' + 
			'<img width="60%" src="/images/app-element-tweet.png" alt="click to add link"/>' + 
			'<p class="apptext">Hashtag:</p><p class="app" id="app-twitter-hash-' + count + '">No hash tag added - click to add</p>' +
			'</fieldset>');
	$('.app-twitter-hash').click(function(){
		elementId = $(this).find('.app').attr('id');
		//Set the dialog header and label
		$('.ui-dialog-title').text('Hash text');
		$('#dialog-single-input-label').text('Enter the text of your hash code (remember it can\'t have spaces, and don\'t include the hash):');
		//Set the dialog passed data and open dialog
		$('#dialog-single-input').data('elementId', elementId);
		$('#dialog-single-input').data('inputType', 'hash tag');
		$('#dialog-single-input').data('inputMaxLength', '500');
		$('#dialog-single-input').data('regex', "^\\w+$");
		$('#dialog-single-input').dialog('open');
	});
}

function createHome() {
	$('#app-screen-content').append('<div id="app-home" style="text-align: center;">' +
			'<img id="app-home-img" width="80%" src="/images/logo.png"/>' + 
			'<p class="app" id="app-home-text">Two Screen</p>' +
			'</div>');
	$('#app-home-img').click(function(){
		elementId = "app-home-img";
		//Set the dialog header and label
		$('.ui-dialog-title').text('Image location');
		$('#dialog-single-input-label').text('HTML link to image: (include http://)');
		//Set the dialog passed data and open dialog
		$('#dialog-single-input').data('attr', 'src');
		$('#dialog-single-input').data('elementId', elementId);
		$('#dialog-single-input').data('inputType', 'HTML link');
		$('#dialog-single-input').data('inputMaxLength', '500');
		$('#dialog-single-input').data('regex', "^(http|https)://(\\w+.|\\w+.\\w+.)(\\w+/|\\w+.\\w+/)+(\\w|-|_)+(.jpg|.png|.svg|.gif|.jpeg)$");
		$('#dialog-single-input').dialog('open');
	});
	$('#app-home-text').click(function(){
		elementId = "app-home-text";
		//Set the dialog header and label
		$('.ui-dialog-title').text('Home text editor');
		$('#dialog-single-input-label').text('Home text:');
		//Set the dialog passed data and open dialog
		$('#dialog-single-input').data('elementId', elementId);
		$('#dialog-single-input').data('inputType', 'home text');
		$('#dialog-single-input').data('inputMaxLength', '20');
		$('#dialog-single-input').dialog('open');
	});
}